<?php

namespace App\Http\Controllers\Api;

use App\Model\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;

class BaseController extends Controller
{
    protected $model = null;
    protected $user = null;
    const SUCCESS = 20000;  // 成功
    const ERROR = 50000;    // 失败
    const PARAM_ERROR = 50001;    // 参数错误
    const ERROR_HAVE_NO_RIGHT = 50002; // 没有操作权限
    const LOGIN_ERROR = 50003;    // 密码错误
    const TOKEN_ILLEGALITY = 50008; //非法 token
    const TOKEN_INVALID = 50014;    // token 已过期
    const CLOSE_ROOM_ERROR = 50015;    // 关闭房间失败
    const ROOM_INFO_ERROR = 50016;    // 房间信息错误
    const MONTH_WATER_STATISTICS = 50017;    // 房间信息错误

    const MESSAGE = [
        self::SUCCESS => '操作成功',
        self::ERROR => '操作失败',
        self::LOGIN_ERROR => '账号或密码错误',
        self::PARAM_ERROR => '参数错误',
        self::TOKEN_ILLEGALITY => '非法 token',
        self::TOKEN_INVALID => 'token 已过期',
        self::ERROR_HAVE_NO_RIGHT => '没有操作权限',
        self::ROOM_INFO_ERROR => '房间信息错误',
        self::CLOSE_ROOM_ERROR => '关闭房间失败',
        self::MONTH_WATER_STATISTICS => '上月流水统计已经生成'
    ];

    public function __construct(Request $request)
    {
        $this->cross();
        $token = $request->header('x-token') ?? '';
        if ($token) $this->user = Users::findByToken($token);
        ini_set('memory_limit', '128M');
    }

    public function cross()
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:GET,POST,PATCH,PUT,OPTIONS');
    }

    protected function toJson($code = self::SUCCESS, $data = [], $message = '')
    {
        return Response::json(['data' => $data, 'message' => $message ?: self::MESSAGE[$code], 'code' => $code]);
    }

    /**
     * 重置api接口返回的结果
     *
     * @param mixed $result
     * @return \Illuminate\Http\JsonResponse
     */
    protected function parseApiResult($result)
    {
        $code = $result['code'] ?? -1;
        $data = $result['data'] ?? [];
        $message = $result['msg'] ?? '';
        return $this->toJson(intval($code) == 0 ? self::SUCCESS : self::ERROR, $data, $message);
    }
}
